// 渲染数据到页面
const renderList = async () => {
  try {
    const res = await axios.get("/students");
    // console.log(res);
    const htmlArr = res.data.map((item) => {
      return `
      <tr>
        <td>${item.name}</td>
        <td>${item.age}</td>
        <td>${item.gender === 0 ? "男" : "女"}</td>
        <td>${item.group}</td>
        <td>${item.hope_salary}</td>
        <td>${item.salary}</td>
        <td>${item.province}${item.city}${item.area}</td>
        <td>
          <a href="javascript:;" class="text-success mr-3"><i data-id=${
            item.id
          } class="bi bi-pen"></i></a>
          <a href="javascript:;" class="text-danger"><i data-id=${
            item.id
          } class="bi bi-trash"></i></a>
        </td>
      </tr>
      `;
    });
    document.querySelector(".list").innerHTML = htmlArr.join("");
    document.querySelector(".total").innerHTML = res.data.length;
  } catch (err) {
    console.log(err);
  }
};
renderList();

// 获取模态框
const modalBox = new bootstrap.Modal(document.querySelector("#modal"));

// 获取省市区dom元素
const p = document.querySelector("[name=province]");
const c = document.querySelector("[name=city]");
const a = document.querySelector("[name=area]");
const form = document.querySelector("#form");

// 删除编辑
document.querySelector(".list").addEventListener("click", async (e) => {
  const id = e.target.dataset.id;
  if (e.target.classList.contains("bi-trash")) {
    // 删除按钮
    try {
      await axios.delete(`/students/${id}`);
      alert("删除成功");
      renderList();
    } catch (err) {
      // console.dir(err)
      console.log(err.response.data.message);
    }
  } else if (e.target.classList.contains("bi-pen")) {
    // 修改按钮
    document.querySelector(".modal-title").innerHTML = "修改学员";
    // 给这个模态框一个标识  区分使用修改打开的
    modalBox.id = id;
    // 获取这个id学员的数据
    const { data } = await axios.get(`/students/${id}`);
    console.log(data);
    // 将数据遍历到模态框里面
    for (const k in data) {
      const ipt = document.querySelector(`[name="${k}"]`);
      if (k !== "gender") {
        ipt !== null && (ipt.value = data[k]);
      } else {
        const genders = document.querySelectorAll("[name=gender]");
        // 获取男女12的为数组作为数组的下标
        genders[data.gender].checked = true;
      }
    }

    await renderProvince(data.province);
    await renderCity(data.city);
    await renderArea(data.area);

    modalBox.show();
  }
});

// 点击添加按钮打开模态框
document.querySelector("#openModal").addEventListener("click", async () => {
  form.reset();
  await renderCity();
  await renderArea();
  document.querySelector(".modal-title").innerHTML = "添加学员";
  console.log(modalBox.id)
  modalBox.id = "add";
  modalBox.show();
});
// 确认 按钮添加信息
document.querySelector("#submit").addEventListener("click", async () => {
  const data = serialize(form,{hash:true})
  // 处理数据转换成数字类型
  for (const k in data) {
    if (isNaN(data[k])===false){
      data[k]= +data[k];
    }
  }
  // isNaN true不是数字 false是数字
  if (modalBox.id="add"){
    try {
      const res = await axios.post("/students",data)
      alert("添加成功！")
      modalBox.hide()
      renderList()
    }catch (e) {
      console.log(e.response.data.message)
    }
  }else{
      const id = modalBox.id
      try{
        const res = await axios.post(`/students/${id}`,data)
        alert(res.message)
        modalBox.hide()
        renderList()
      }catch (e) {
        console.log(e.response.data.message)
      }
  }

})


// 获取省市区数据
// 获取省份
async function renderProvince(province = "") {
  const { data } = await axios.get("/api/province");
  const pArr = data.map((item) => {
    return `<option value="${item}">${item}</option>`;
  });
  p.innerHTML = pArr.join("");
  province !== "" && (p.value = province);
}
// 获取市
async function renderCity(city = "") {
  const { data } = await axios.get("/api/city", { params: { pname: p.value } });
  const cArr = data.map((item) => {
    return `<option value="${item}">${item}</option>`;
  });
  c.innerHTML = cArr.join("");
  city !== "" && (c.value = city);
}
// 获取区
async function renderArea(area = "") {
  const { data } = await axios.get("/api/area", {
    params: { pname: p.value, cname: c.value },
  });
  const aArr = data.map((item) => {
    return `<option value="${item}">${item}</option>`;
  });
  a.innerHTML = aArr.join("");
  area !== "" && (a.value = area);
}

// 初始化省市区
const initInfo = async () => {
  await renderProvince();
  await renderCity();
  await renderArea();
};
initInfo();

// 省市区联动
// 省市联动
p.addEventListener("change", async () => {
  await renderCity();
  await renderArea();
});
// 市区联动
c.addEventListener("change", async () => {
  await renderArea();
});
